//
//  TableShowImageCell+Config.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/10/13.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import RxSwift
import RxGesture
import SKPhotoBrowser
import Kingfisher

public extension TableShowImageCell {
    
    // MARK: - bind前 执行
    func layoutViews() {
        contentView.addSubview(showImageView)
        showImageView.rx.tapGesture().when(.ended).subscribe(onNext: { [weak self] _ in
            self?.showPhotos()
          }).disposed(by: stepBag)
    }
    
    // MARK: - bind后 执行
    func loadData() {
        /// TableShowImageCellModel  TableShowImageConfig
        guard let cellModel = self.info as? TableShowImageCellModel, let config = cellModel.model as? TableShowImageConfig else {
            return
        }
    
        if !cellModel.isConfigDone { /// 执行一次配置
            cellModel.isConfigDone = true
            cellModel.once(showImageView, cell: self)
        }
        cellModel.every(showImageView, cell: self)
        
        if !cellModel.showByDefaultWay { return } /// 默认加载方式
        
        /// 延迟加载
        if (config.isDelay) {
            return
        }
        
        /// 加载数据
        loadImageActivity()
        
    }
    
    /// 加载数据
    func loadImageActivity() {
        
        guard let cellModel = self.info as? TableShowImageCellModel, let config = cellModel.model as? TableShowImageConfig else {
            return
        }
        
        /// 防止闪动
        showImageView.isHidden =  true
        
        /// 已缓存过大小 直接加载
        /// 不需要自适应 直接写死
        if config.imageViewSize.height > 0 || !config.isFit {
            config.loadAll(showImageView)
            return
        }
        /// 初次加载图片
        showImageView.kf.setImage(with: URL(string: config.url ?? ""), placeholder: config.placeholderImage) { [weak self] result in
            switch result {
               case .success(let value):
                    let size = config.updateWidthOrHeight(value.image.size)
                    guard let imageView = self?.showImageView else { return }
                    config.loadAll(imageView)
                    cellModel.cellHeight = size.height + config.vTopCons - config.vBottomCons
//                    cellModel.postTableService(.updatesTable)
                    cellModel.postTableService(.updatesCellHeight)
               case .failure(let error):
                   print("Job failed: \(error.localizedDescription)")
               }
        }
    }
    
    
    /// 显示图片
    func showPhotos()  {
        guard let cellModel = self.info as? TableShowImageCellModel, let config = cellModel.model as? TableShowImageConfig else {
            return
        }
        
        if let url = config.url {
            showPhotosBrowser([url])
        }
        
    }

}
